package com.qfedu.dtboot.service.impl;

import com.qfedu.dtboot.dao.SysUserDao;
import com.qfedu.dtboot.entity.SysMenu;
import com.qfedu.dtboot.dao.SysMenuDao;
import com.qfedu.dtboot.service.SysMenuService;
import com.qfedu.dtboot.util.DataGridResult;
import com.qfedu.dtboot.util.Query;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单管理(SysMenu)表服务实现类
 *
 * @author ykx
 * @since 2022-09-27 13:02:35
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuDao sysMenuDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public List<SysMenu> queryListAll() {
        return sysMenuDao.queryListAll();
    }

    @Override
    public List<SysMenu> queryMenuList(Long userId) {
        List<SysMenu> menuList = sysMenuDao.queryMenuListByUserId(userId);
        for (SysMenu menu : menuList) {
            menu.setList(querySubMenuList(menu.getMenuId()));
        }
        return menuList;
    }

    @Override
    public DataGridResult getPageList(Query query) {
        List<SysMenu> rows = sysMenuDao.queryList(query);
        Integer total = sysMenuDao.queryTotal();
        return new DataGridResult(rows,total);
    }

    private List<SysMenu> querySubMenuList(Long parentId){
        List<SysMenu> subMenuList = sysMenuDao.queryListParentId(parentId);
        if (subMenuList!=null){
            for (SysMenu menu : subMenuList) {
                menu.setList(querySubMenuList(menu.getMenuId()));
            }
        }
        return subMenuList;
    }

    private List<SysMenu> queryListParentId(Long parentId,List<Long> menuIdList){
        List<SysMenu> menuList = sysMenuDao.queryListParentId(parentId);
        if (menuIdList==null){
            return null;
        }
        //过滤当前用户有权访问的子菜单列表
        List<SysMenu> userMenuList = new ArrayList<>();
        for (SysMenu sysMenu : menuList) {
            userMenuList.add(sysMenu);
        }

        return userMenuList;
    }

    private void getMenuTreeList(List<SysMenu> menuList,List<Long> menuIdList){
        for (SysMenu menu : menuList) {
            List<SysMenu> subMenuList = queryListParentId(menu.getMenuId(),menuIdList);
            getMenuTreeList(subMenuList,menuIdList);
            menu.setList(subMenuList);
        }
    }

    public List<SysMenu> getAllMenuList(List<Long> menuIdList){
        List<SysMenu> menuList = queryListParentId(0L, menuIdList);
        getMenuTreeList(menuList,menuIdList);
        return menuList;
    }

    public List<SysMenu> getUserMenuList(Long userId){
        if (userId==1){
            return getAllMenuList(null);
        }
        List<Long> menuIdList = sysUserDao.queryAllMenuId(userId);
        return getAllMenuList(menuIdList);
    }

}
